//
//  YRJSearchViewController.m
//  YanRenjie
//
//  Created by dllo on 15/11/3.
//  Copyright (c) 2015年 yanrenjie. All rights reserved.
//

#import "YRJSearchViewController.h"
#import "YRJTripHeader.h"

@interface YRJSearchViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *searchHistoryArray;
@property(nonatomic, retain)NSMutableArray *hotSearchHistoryArray;
@property(nonatomic, retain)NSString *stringURL;
@property(nonatomic, retain)NSMutableArray *searchResultArray;
@end

@implementation YRJSearchViewController
- (void)dealloc {
    [_searchBar release];
    [_tableView release];
    [_searchHistoryArray release];
    [_hotSearchHistoryArray release];
    [_stringURL release];
    [_searchResultArray release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor brownColor];
    // 添加搜索栏
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake((10.0 / 375) * WIDTH, (12.0 / 667) * HEIGHT, (40.0 / 375) * WIDTH, (280.0 / 667) * HEIGHT)];
    self.searchBar.backgroundColor = [UIColor clearColor];
    self.searchBar.layer.borderWidth = 0;
    self.navigationItem.titleView = self.searchBar;
    self.searchBar.placeholder = @"搜索用户、目的地、帖子、折扣";   // 所搜栏占位字
    [_searchBar release];
    self.searchBar.delegate = self;
    
    [self createTableView];
    self.hotSearchHistoryArray = [NSMutableArray array];
    self.searchHistoryArray = [NSMutableArray array];

}


- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = (60.0 / 667) * HEIGHT;
    [self createData];
}


- (void)createData {
    NSString *strURL = @"http://open.qyer.com/qyer/search/hot_history?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=867739013144832&track_app_version=6.8.1&track_app_channel=hiapk&track_device_info=bbk77_cu_ics2&track_os=Android4.0.4&app_installtime=1445390305001&lat=38.883559&lon=121.54435";
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *tempArray = [NSArray arrayWithArray:dic[@"data"]];
        self.hotSearchHistoryArray = [NSMutableArray array];
        for (NSString *tempStr in tempArray) {
            [self.hotSearchHistoryArray addObject:tempStr];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}


#pragma mark - tableView 的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchHistoryArray.count == 0) {
        return self.hotSearchHistoryArray.count;
    } else {
        if (section == 0) {
            return self.searchHistoryArray.count;
        } else {
            return self.hotSearchHistoryArray.count;
        }
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *hotSearchReuse = @"hotSearchReuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:hotSearchReuse];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:hotSearchReuse];
    }
    cell.textLabel.text = self.hotSearchHistoryArray[indexPath.row];
    return cell;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.searchHistoryArray.count == 0) {
        return 1;
    } else {
        return 2;
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (self.searchHistoryArray.count == 0) {
        return @"热门搜索";
    } else {
        if (section == 0) {
            return @"搜索历史";
        } else {
            return @"热门搜索";
        }
    }
}


#pragma mark - UISearchBar 的协议方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [self.searchBar setShowsCancelButton:YES animated:YES];
    
    // 把取消按钮改成中文
    for (UIView *subView in [self.searchBar.subviews[0] subviews]) {
        if ([subView isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)subView;
            [button setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
    self.searchBar.tintColor = [UIColor grayColor];
    self.searchBar.barTintColor = [UIColor whiteColor];
    return YES;
}


- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
    [self.searchBar setShowsCancelButton:NO animated:YES];
}


// 搜索内容变化时调用此方法
// 搜索按钮按下时触发此方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self loadSearchDataWithKeyString:searchBar.text];
}


// 加载搜索关键词数据
// keyStr: 搜索关键词字符串
- (void)loadSearchDataWithKeyString:(NSString *)keyStr {
    // 中文搜索词url转码
    NSString *key = [keyStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.stringURL = [NSString stringWithFormat:@"%@%@%@", @"http://open.qyer.com/qyer/search/index?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&keyword=", key, @"&page=1&place_field=country%7Ccity%7Cpoi&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&type=place&v=1"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:self.stringURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"搜索%@", keyStr);
        NSDictionary *dic = responseObject;
        self.searchResultArray = [YRJSearchDestinationModel baseModelByArr:dic[@"data"][@"entry"]];
        [self.searchBar resignFirstResponder];
        YRJSearchResultViewController *searchResultVC = [[YRJSearchResultViewController alloc] init];
        [self.navigationController pushViewController:searchResultVC animated:YES];
        searchResultVC.keyString = key;
        searchResultVC.searchTextString = self.searchBar.text;
        NSLog(@"%@", key);
        [searchResultVC release];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"搜索%@网络请求失败", keyStr);
    }];
    
}


// 点击热门搜索直接进入相应的搜索页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.searchBar.text = self.hotSearchHistoryArray[indexPath.row];
    NSString *key = [self.hotSearchHistoryArray[indexPath.row] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    YRJSearchResultViewController *searchResultVC = [[YRJSearchResultViewController alloc] init];
    [self.navigationController pushViewController:searchResultVC animated:YES];
    searchResultVC.keyString = key;
    searchResultVC.searchTextString = self.searchBar.text;
    NSLog(@"%@", key);
    [searchResultVC release];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
